﻿namespace AddressBook.Business.Person
{
	#region "Using Statements"
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;

	using Csla;
	using Csla.Data;
	#endregion

	public class PhoneNumberTypeList : NameValueListBase<Int32, String>
	{
		#region  "Business Methods"

		public static int DefaultPhoneNumberType()
		{
			PhoneNumberTypeList list = GetList();

			if (list.Count > 0)
			{
				return list.Items[0].Key;
			}
			else
			{
				throw new NullReferenceException("No phone number types available; default phone number type can not be returned");
			}
		}

		#endregion

		#region  "Factory Methods"

		private static PhoneNumberTypeList list;

		public static PhoneNumberTypeList GetList()
    {
			if (list == null)
			{
				list = DataPortal.Fetch<PhoneNumberTypeList>();
			}

      return list;
    }

    /// <summary>
		/// Clears the in-memory PhoneNumberTypeList cache
    /// so the list of address types is reloaded on
    /// next request.
    /// </summary>
    public static void InvalidateCache()
    {
      list = null;
    }

		private PhoneNumberTypeList()
    { /* require use of factory methods */ }

    #endregion

		#region  Data Access

		private void DataPortal_Fetch()
		{
			this.RaiseListChangedEvents = false;

			using (var ctx = ContextManager<AddressBook.Business.Model.AddressBookDataContext>.GetManager(AddressBook.Business.Model.Database.AddressBook))
			{
				List<NameValuePair> data = (from type in ctx.DataContext.PhoneNumberTypes
																		select new NameValuePair(type.Id, type.Name)).ToList<NameValuePair>();

				this.IsReadOnly = false;

				this.AddRange(data);

				this.IsReadOnly = true;
			}

			this.RaiseListChangedEvents = true;
		}

		#endregion
	}
}
